﻿using FTBS.Models.BLO;
using FTBS.Models.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using PagedList;
using FTBS.Models.Entities.Concert;

namespace FTBS.Controllers
{
    public class TheaterController : Controller
    {
        private TheaterBLO _theaterBLO = new TheaterBLO();
        //private SettingTheaterBLO _settingTheaterBlo = new SettingTheaterBLO();

        /// <summary>
        /// Load list of Theater
        /// </summary>
        /// <returns></returns>
        public ActionResult Index(string sortOrder, string currentFilter, string searchString, int? page, bool? isSortDescending)
        {
            if (this.Session["RoleName"] == null || this.Session["UserName"] == null || this.Session["Account"] == null || this.Session["RoleName"].ToString().Trim() != "Staff")
            {
                return Redirect("/Home/Announcement");
            }
            List<Theater> listTheater = new List<Theater>();
            listTheater = _theaterBLO.GetAllTheaterInfo();

            ViewBag.NameSortParm = "theater_name_desc";
            ViewBag.CurrentSort = sortOrder;

            if (searchString != null)
            {
                page = 1;
            }
            else
            {
                searchString = currentFilter;
            }

            ViewBag.CurrentFilter = searchString;
            ViewBag.IsSortDes = false;

            if (!String.IsNullOrEmpty(searchString))
            {

                listTheater = listTheater.Where(theater => theater.TheaterName.ToUpper().Contains(searchString.ToUpper())
                                  || theater.Address.ToUpper().Contains(searchString.ToUpper())
                                  || theater.PhoneNumber.ToUpper().Contains(searchString.ToUpper())).ToList();
            }

            switch (sortOrder)
            {
                case "theater_name_desc":
                    if (isSortDescending == true)
                    {
                        listTheater = listTheater.OrderByDescending(theater => theater.TheaterName).ToList();
                        ViewBag.IsSortDes = false;
                    }
                    else
                    {
                        listTheater = listTheater.OrderBy(theater => theater.TheaterName).ToList();
                        ViewBag.IsSortDes = true;
                    }
                    break;
                case "address_desc":
                    if (isSortDescending == true)
                    {
                        listTheater = listTheater.OrderByDescending(theater => theater.Address).ToList();
                        ViewBag.IsSortDes = false;
                    }
                    else
                    {
                        listTheater = listTheater.OrderBy(theater => theater.Address).ToList();
                        ViewBag.IsSortDes = true;
                    }
                    break;
                case "phone_desc":
                    if (isSortDescending == true)
                    {
                        listTheater = listTheater.OrderByDescending(theater => theater.PhoneNumber).ToList();
                        ViewBag.IsSortDes = false;
                    }
                    else
                    {
                        listTheater = listTheater.OrderBy(theater => theater.PhoneNumber).ToList();
                        ViewBag.IsSortDes = true;
                    }
                    break;
                default:
                    listTheater = listTheater.OrderBy(theater => theater.TheaterName).ToList();
                    ViewBag.IsSortDes = false;
                    break;
            }

            int pageSize = 5;
            int pageNumber = (page ?? 1);

            return View(listTheater.ToPagedList(pageNumber, pageSize));
        }

        /// <summary>
        /// Go to Create page
        /// </summary>
        /// <returns></returns>
        public ActionResult Create()
        {
            if (this.Session["RoleName"] == null || this.Session["UserName"] == null || this.Session["Account"] == null || this.Session["RoleName"].ToString().Trim() != "Staff")
            {
                return Redirect("/Home/Announcement");
            }
            IEnumerable<User> listUser = new List<User>();
            listUser = _theaterBLO.GetAllSupplier();
            ViewBag.ListSupplier = new SelectList(listUser.ToList(), "UserName", "FullName");
            SettingTheaterConcertEntity modelCreated = new SettingTheaterConcertEntity();

            //Flag to check validate Theater and Setting
            modelCreated.IsCreatingTheater = true;

            //Flag to valid theater and setting
            modelCreated.IsValidTheater = true;
            modelCreated.IsValidSetting = false;
            modelCreated.IsExistTheaterName = false;
            modelCreated.IsFinish = false;

            //Model created of previous step
            ViewBag.ModelCreated = modelCreated;

            //Flag of Step creat Theater or create Setting or SuccessFull
            ViewBag.StepTheater = true;
            ViewBag.StepSetting = false;
            ViewBag.IsStepSuccess = false;
            ViewBag.IsStepFail = false;

            //Result of Add new Theater and Setting
            ViewBag.ResultAddTheaterAndSetting = false;


            return View();
        }

        /// <summary>
        /// Event Create new Theater
        /// </summary>
        /// <param name="theater"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Create(SettingTheaterConcertEntity theaterAndSetting, HttpPostedFileBase fileCreate)
        {
            if (this.Session["RoleName"] == null || this.Session["UserName"] == null || this.Session["Account"] == null || this.Session["RoleName"].ToString().Trim() != "Staff")
            {
                return Redirect("/Home/Announcement");
            }
            SettingTheaterConcertEntity theaterEntity = theaterAndSetting;
            SettingTheaterConcertEntity settingTheater = theaterAndSetting;
            IEnumerable<User> listUser = new List<User>();
            listUser = _theaterBLO.GetAllSupplier();
            if (fileCreate != null)
            {
                theaterEntity.ImageURL = fileCreate.FileName;
            }
            if (_theaterBLO.IsValidTheater(theaterEntity))
            {
                if (theaterAndSetting.IsCreatingTheater)
                {
                    if (!_theaterBLO.IsExistTheater(theaterEntity))
                    {
                        if (fileCreate != null)
                        {
                            fileCreate.SaveAs(HttpContext.Server.MapPath("~/Image/Theater/") + fileCreate.FileName);
                            theaterEntity.ImageURL = fileCreate.FileName;
                        }
                        //Set property IsValidTheater = false to set flag Create Theater is finish -> move to create Setting
                        theaterAndSetting.IsCreatingTheater = false;
                        theaterAndSetting.IsValidTheater = true;
                        theaterAndSetting.IsValidSetting = false;
                        theaterAndSetting.IsExistTheaterName = false;
                        theaterAndSetting.IsFinish = false;

                        ViewBag.ListSupplier = new SelectList(listUser.ToList(), "UserName", "FullName");
                        ViewBag.ModelCreated = theaterAndSetting;

                        ViewBag.StepTheater = false;
                        ViewBag.StepSetting = true;
                        ViewBag.IsStepSuccess = false;
                        ViewBag.IsStepFail = false;

                        //Result of Add new Theater and Setting
                        ViewBag.ResultAddTheaterAndSetting = false;
                        return View();
                    }
                    else
                    {
                        //Set property IsValidTheater = false to set flag Create Theater is finish -> move to create Setting
                        theaterAndSetting.IsCreatingTheater = true;
                        theaterAndSetting.IsValidTheater = false;
                        theaterAndSetting.IsValidSetting = false;
                        theaterAndSetting.IsExistTheaterName = true;
                        theaterAndSetting.IsFinish = false;

                        ViewBag.ListSupplier = new SelectList(listUser.ToList(), "UserName", "FullName");
                        ViewBag.ModelCreated = theaterAndSetting;

                        ViewBag.StepTheater = true;
                        ViewBag.StepSetting = false;
                        ViewBag.IsStepSuccess = false;
                        ViewBag.IsStepFail = false;

                        //Result of Add new Theater and Setting
                        ViewBag.ResultAddTheaterAndSetting = false;
                        return View();
                    }
                }
                else
                {
                    if (_theaterBLO.IsValidSetting(settingTheater))
                    {
                        //Set property IsValidTheater = false to set flag Create Theater is finish -> move to create Setting
                        theaterAndSetting.IsCreatingTheater = false;
                        theaterAndSetting.IsValidTheater = true;
                        theaterAndSetting.IsValidSetting = true;
                        theaterAndSetting.IsExistTheaterName = false;
                        theaterAndSetting.IsFinish = false;

                        ViewBag.ListSupplier = new SelectList(listUser.ToList(), "UserName", "FullName");

                        ViewBag.StepTheater = false;
                        ViewBag.StepSetting = false;

                        //Add theater and theater's setting
                        var resultAdd = _theaterBLO.AddNewTheaterAndSetting(theaterAndSetting);
                        if (resultAdd == 2)
                        {
                            if (theaterAndSetting.ImageURL != null)
                            {
                                System.IO.File.Delete(HttpContext.Server.MapPath("~/Image/Theater/") + theaterAndSetting.ImageURL);
                            }
                        }
                        ViewBag.ResultAddTheaterAndSetting = resultAdd;

                        //Set property Finish
                        //theaterSettingEntity.IsFinish = true;

                        //Send Model to View
                        ViewBag.ModelCreated = theaterAndSetting;

                        //Set value for StepSuccess or FailStep
                        if (resultAdd == 1)
                        {
                            ViewBag.IsStepSuccess = true;
                            ViewBag.IsStepFail = false;
                        }
                        else if (resultAdd == 2)
                        {
                            ViewBag.IsStepSuccess = false;
                            ViewBag.IsStepFail = true;
                        }
                        else if (resultAdd == 3)
                        {
                            return RedirectToAction("Index");
                        }
                        return View();
                    }
                    else
                    {
                        //Set property IsValidTheater = false to set flag Create Theater is finish -> move to create Setting
                        theaterAndSetting.IsCreatingTheater = false;
                        theaterAndSetting.IsValidTheater = true;
                        theaterAndSetting.IsValidSetting = false;
                        theaterAndSetting.IsExistTheaterName = false;
                        theaterAndSetting.IsFinish = false;

                        ViewBag.ListSupplier = new SelectList(listUser.ToList(), "UserName", "FullName");
                        ViewBag.ModelCreated = theaterAndSetting;

                        ViewBag.StepTheater = false;
                        ViewBag.StepSetting = true;
                        ViewBag.IsStepSuccess = false;
                        ViewBag.IsStepFail = false;

                        //Result of Add new Theater and Setting
                        ViewBag.ResultAddTheaterAndSetting = false;
                        return View();
                    }
                }
            }
            //Set property IsValidTheater = false to set flag Create Theater is finish -> move to create Setting
            theaterAndSetting.IsCreatingTheater = true;
            theaterAndSetting.IsValidTheater = false;
            theaterAndSetting.IsValidSetting = false;
            theaterAndSetting.IsExistTheaterName = false;
            theaterAndSetting.IsFinish = false;

            ViewBag.ListSupplier = new SelectList(listUser.ToList(), "UserName", "FullName");
            ViewBag.ModelCreated = theaterAndSetting;

            ViewBag.StepTheater = true;
            ViewBag.StepSetting = false;
            ViewBag.IsStepSuccess = false;
            ViewBag.IsStepFail = false;

            //Result of Add new Theater and Setting
            ViewBag.ResultAddTheaterAndSetting = false;
            return View();

        }

        /// <summary>
        /// Go to Edit page
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult Edit(int id = 0)
        {
            if (this.Session["RoleName"] == null || this.Session["UserName"] == null || this.Session["Account"] == null || this.Session["RoleName"].ToString().Trim() != "Staff")
            {
                return Redirect("/Home/Announcement");
            }
            Theater theater = _theaterBLO.GetTheaterById(id);
            ViewBag.TheaterName = null;
            ViewBag.ListSupplier = new SelectList(_theaterBLO.GetAllSupplier(), "UserName", "FullName", theater.UserName);
            if (theater == null)
            {
                return HttpNotFound();
            }
            return View(theater);
        }

        /// <summary>
        /// Event Edit new Theater
        /// </summary>
        /// <param name="theater"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Edit(Theater theater, HttpPostedFileBase fileImageUpdate)
        {
            if (this.Session["RoleName"] == null || this.Session["UserName"] == null || this.Session["Account"] == null || this.Session["RoleName"].ToString().Trim() != "Staff")
            {
                return Redirect("/Home/Announcement");
            }
            if (ModelState.IsValid)
            {
                Theater theaterEntity = new Theater();
                theaterEntity = _theaterBLO.GetTheaterById(theater.TheaterId);
                if (!theater.TheaterName.Equals(theaterEntity.TheaterName))
                {
                    if (!_theaterBLO.IsExistTheaterUpdate(theater))
                    {
                        if (fileImageUpdate != null)
                        {
                            if (fileImageUpdate.FileName.Equals(theaterEntity.ImageURL))
                            {
                                fileImageUpdate.SaveAs(HttpContext.Server.MapPath("~/Image/Theater/") + fileImageUpdate.FileName);
                                theater.ImageURL = fileImageUpdate.FileName;
                            }
                            else if (!fileImageUpdate.FileName.Equals(theaterEntity.ImageURL))
                            {
                                if (theater.ImageURL != null)
                                {
                                    System.IO.File.Delete(HttpContext.Server.MapPath("~/Image/Theater/") + theaterEntity.ImageURL);
                                }
                                fileImageUpdate.SaveAs(HttpContext.Server.MapPath("~/Image/Theater/") + fileImageUpdate.FileName);
                                theater.ImageURL = fileImageUpdate.FileName;
                            }
                        }

                        ViewBag.TheaterName = null;
                        _theaterBLO.EditTheater(theater);
                        return RedirectToAction("Index");
                    }
                    else
                    {
                        ViewBag.TheaterName = theater.TheaterName;
                        ViewBag.ListSupplier = new SelectList(_theaterBLO.GetAllSupplier(), "UserName", "FullName", theater.UserName);
                        return View(theater);
                    }
                }
                else
                {
                    if (fileImageUpdate != null)
                    {
                        if (fileImageUpdate.FileName.Equals(theaterEntity.ImageURL) || string.Empty.Equals(theaterEntity.ImageURL))
                        {
                            fileImageUpdate.SaveAs(HttpContext.Server.MapPath("~/Image/Theater/") + fileImageUpdate.FileName);
                            theater.ImageURL = fileImageUpdate.FileName;
                        }
                        else if (!fileImageUpdate.FileName.Equals(theaterEntity.ImageURL))
                        {
                            if (theater.ImageURL != null)
                            {
                                System.IO.File.Delete(HttpContext.Server.MapPath("~/Image/Theater/") + theaterEntity.ImageURL);
                            }
                            fileImageUpdate.SaveAs(HttpContext.Server.MapPath("~/Image/Theater/") + fileImageUpdate.FileName);
                            theater.ImageURL = fileImageUpdate.FileName;
                        }
                    }

                    ViewBag.TheaterName = null;
                    _theaterBLO.EditTheater(theater);
                    return RedirectToAction("Index");
                }
            }
            else
            {
                ViewBag.TheaterName = null;
                ViewBag.ListSupplier = new SelectList(_theaterBLO.GetAllSupplier(), "UserName", "FullName", theater.UserName);
                return View(theater);
            }
        }

        [HttpDelete, ActionName("Delete")]
        public ActionResult Delete(int id = 0)
        {
            if (this.Session["RoleName"] == null || this.Session["UserName"] == null || this.Session["Account"] == null || this.Session["RoleName"].ToString().Trim() != "Staff")
            {
                return Redirect("/Home/Announcement");
            }
            if (_theaterBLO.IsTheaterUsedInScheduleAndBooked(id))
            {
                TempData["CanNotDelete"] = true;
                return RedirectToAction("Index");
            }
            else
            {
                Theater t = _theaterBLO.GetTheaterById(id);
                if (t == null)
                {
                    HttpNotFound();
                }
                _theaterBLO.DeleteTheater(t);
                return RedirectToAction("Index");
            }

        }
    }
}
